package com.xu.controller.center;

import com.xu.controller.BaseController;
import com.xu.pojo.Users;
import com.xu.pojo.bo.center.CenterUserBO;
import com.xu.resource.FileUpload;
import com.xu.service.center.CenterUserService;
import com.xu.utils.CookieUtils;
import com.xu.utils.DateUtil;
import com.xu.utils.JSONResult;
import com.xu.utils.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author anan
 * @create 2022-03-03 18:45
 */

@RestController
@RequestMapping("userInfo")
@Api(value = "用户信息接口", tags = "用户信息相关接口")
public class CenterUserController extends BaseController{

    @Autowired
    private CenterUserService centerUserService;

    @Autowired
    private FileUpload fileUpload;
    @ApiOperation(value = "用户头像修改", notes = "用户头像修改", httpMethod = "POST")
    @PostMapping("/uploadFace")
    public JSONResult uploadFace(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam String userId,
            @ApiParam(name = "file", value = "用户头像", required = true)
            MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response){
        //定义保存头像的地址
        //String fileSpace = IMAGE_USER_FACE_LOCATION;
        String fileSpace = fileUpload.getImageUserFaceLocation();
        //为路径上每一个用户增加一个userId, 用于区分不同用户上传
        String uploadPathPrefix = File.separator + userId;
        String imgUrlDetail = null;
        //开始文件上传
        if(file != null){
            String fileName = file.getOriginalFilename();
            FileOutputStream fileOutputStream = null;
            try {
                if(!StringUtils.isBlank(fileName)){
                    String[] fileNameArr = fileName.split("\\.");
                    String suffix = fileNameArr[fileNameArr.length - 1];
                    if(!suffix.equalsIgnoreCase("png") &&
                            !suffix.equalsIgnoreCase("jpg") &&
                            !suffix.equalsIgnoreCase("jpeg")){
                        return JSONResult.errorMsg("文件格式不正确！");
                    }
                    String newFileName = "face-" + userId +  "." + suffix;
                    String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
                    //头像在URL上的后半段地址
                    imgUrlDetail = "/" + userId + "/" + newFileName;

                    File outFile = new File(finalFacePath);
                    if(outFile.getParentFile() != null){
                        //创建文件夹
                        outFile.getParentFile().mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(outFile);
                    InputStream inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(fileOutputStream != null){
                    try {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else{
            return JSONResult.errorMsg("文件不能为空");
        }
        //获取图片服务地址
        String imageServerUrl = fileUpload.getImageServerUrl();
        //由于浏览器可能存在缓存的情况，所以在这里，我们需要加上时间戳来保证更新后的图片可以及时刷新。
        String finalUserFaceUrl = imageServerUrl + imgUrlDetail
                + "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
        Users userRes = centerUserService.updateUserFace(userId, finalUserFaceUrl);

        userRes = setUsersNull(userRes);
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userRes), true);

        //TODO 后续要改，增加令牌Token，会整合进redis,分布式会话

        return JSONResult.ok();
    }


    @ApiOperation(value = "修改用户信息", notes = "修改用户信息", httpMethod = "POST")
    @PostMapping("/update")
    public JSONResult userInfo(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam String userId,
            @RequestBody @Valid CenterUserBO centerUserBO,
            BindingResult result,
            HttpServletRequest request,
            HttpServletResponse response){
        if(result.hasErrors()){
            Map<String, String> errors = getErrors(result);
            return JSONResult.errorMap(errors);
        }
        Users userRes = centerUserService.updateUsersInfo(userId, centerUserBO);
        userRes = setUsersNull(userRes);
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userRes), true);

        // TODO 后续要改，增加令牌token, 会整合进redis, 分布式会话
        return JSONResult.ok(userRes);
    }

    private Map<String, String> getErrors(BindingResult result){
        Map<String, String> map = new HashMap<>();
        List<FieldError> fieldErrors = result.getFieldErrors();
        for(FieldError error : fieldErrors){
            String errorField = error.getField();
            String errorMsg = error.getDefaultMessage();
            map.put(errorField, errorMsg);
        }
        return map;
    }

    private Users setUsersNull(Users userRes){
        userRes.setPassword(null);
        userRes.setUpdatedTime(null);
        userRes.setCreatedTime(null);
        userRes.setBirthday(null);
        userRes.setEmail(null);
        userRes.setMobile(null);
        userRes.setRealname(null);
        return userRes;
    }

}
